'use strict';

const { Service } = require('egg');

class IncomingInvoiceService extends Service {
  /**
   * 获取进项发票列表
   * @param {Object} query - 查询参数
   * @param {Number} organizationId - 组织ID
   */
  async getIncomingInvoices(query, organizationId) {
    const { ctx } = this;
    const { page = 1, pageSize = 20, invoiceNumber, sellerName, buyerName, startDate, endDate } = query;
    
    try {
      const where = { organizationId };
      
      // 添加查询条件
      if (invoiceNumber) {
        where.invoiceNumber = { [ctx.app.Sequelize.Op.like]: `%${invoiceNumber}%` };
      }
      
      if (sellerName) {
        where.sellerName = { [ctx.app.Sequelize.Op.like]: `%${sellerName}%` };
      }
      
      if (buyerName) {
        where.buyerName = { [ctx.app.Sequelize.Op.like]: `%${buyerName}%` };
      }
      
      if (startDate && endDate) {
        where.invoiceDate = {
          [ctx.app.Sequelize.Op.between]: [new Date(startDate), new Date(endDate)]
        };
      }
      
      const result = await ctx.model.IncomingInvoiceModel.findAndCountAll({
        where,
        limit: parseInt(pageSize),
        offset: (parseInt(page) - 1) * parseInt(pageSize),
        order: [['createdAt', 'DESC']]
      });
      
      return {
        items: result.rows,
        total: result.count,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      };
    } catch (error) {
      ctx.logger.error('[IncomingInvoice] 获取发票列表失败:', error);
      throw error;
    }
  }
  
  /**
   * 根据ID获取进项发票详情
   * @param {Number} id - 发票ID
   * @param {Number} organizationId - 组织ID
   */
  async getIncomingInvoiceById(id, organizationId) {
    const { ctx } = this;
    
    try {
      const invoice = await ctx.model.IncomingInvoiceModel.findOne({
        where: {
          id,
          organizationId
        }
      });
      
      if (!invoice) {
        ctx.throw(404, '发票不存在');
      }
      
      return invoice;
    } catch (error) {
      ctx.logger.error('[IncomingInvoice] 获取发票详情失败:', error);
      throw error;
    }
  }
  
  /**
   * 创建进项发票
   * @param {Object} invoiceData - 发票数据
   * @param {Number} organizationId - 组织ID
   */
  async createIncomingInvoice(invoiceData, organizationId) {
    const { ctx } = this;
    
    try {
      // 检查发票号码是否已存在
      const existingInvoice = await ctx.model.IncomingInvoiceModel.findOne({
        where: {
          invoiceNumber: invoiceData.invoiceNumber,
          organizationId
        }
      });
      
      if (existingInvoice) {
        ctx.throw(400, '发票号码已存在');
      }
      
      const invoice = await ctx.model.IncomingInvoiceModel.create({
        ...invoiceData,
        organizationId
      });
      
      ctx.logger.info(`[IncomingInvoice] 创建发票: ${invoice.invoiceNumber}`);
      return invoice;
    } catch (error) {
      ctx.logger.error('[IncomingInvoice] 创建发票失败:', error);
      throw error;
    }
  }
  
  /**
   * 更新进项发票
   * @param {Number} id - 发票ID
   * @param {Object} invoiceData - 发票数据
   * @param {Number} organizationId - 组织ID
   */
  async updateIncomingInvoice(id, invoiceData, organizationId) {
    const { ctx } = this;
    
    try {
      const invoice = await ctx.model.IncomingInvoiceModel.findOne({
        where: {
          id,
          organizationId
        }
      });
      
      if (!invoice) {
        ctx.throw(404, '发票不存在');
      }
      
      // 检查发票号码是否被其他发票使用
      if (invoiceData.invoiceNumber && invoiceData.invoiceNumber !== invoice.invoiceNumber) {
        const existingInvoice = await ctx.model.IncomingInvoiceModel.findOne({
          where: {
            invoiceNumber: invoiceData.invoiceNumber,
            organizationId,
            id: { [ctx.app.Sequelize.Op.ne]: id }
          }
        });
        
        if (existingInvoice) {
          ctx.throw(400, '发票号码已存在');
        }
      }
      
      await invoice.update(invoiceData);
      ctx.logger.info(`[IncomingInvoice] 更新发票: ${invoice.invoiceNumber}`);
      return invoice;
    } catch (error) {
      ctx.logger.error('[IncomingInvoice] 更新发票失败:', error);
      throw error;
    }
  }
  
  /**
   * 删除进项发票
   * @param {Number} id - 发票ID
   * @param {Number} organizationId - 组织ID
   */
  async deleteIncomingInvoice(id, organizationId) {
    const { ctx } = this;
    
    try {
      const invoice = await ctx.model.IncomingInvoiceModel.findOne({
        where: {
          id,
          organizationId
        }
      });
      
      if (!invoice) {
        ctx.throw(404, '发票不存在');
      }
      
      await invoice.destroy();
      ctx.logger.info(`[IncomingInvoice] 删除发票: ${invoice.invoiceNumber}`);
    } catch (error) {
      ctx.logger.error('[IncomingInvoice] 删除发票失败:', error);
      throw error;
    }
  }
  
  /**
   * 创建或更新进项发票
   * @param {Object} invoiceData - 发票数据
   * @param {Number} organizationId - 组织ID
   */
  async createOrUpdateIncomingInvoice(invoiceData, organizationId) {
    const { ctx } = this;
    
    try {
      // 检查发票是否已存在
      const existingInvoice = await ctx.model.IncomingInvoiceModel.findOne({
        where: {
          invoiceNumber: invoiceData.invoiceNumber,
          organizationId: organizationId
        }
      });
      
      const invoicePayload = {
        invoiceNumber: invoiceData.invoiceNumber,
        invoiceCode: invoiceData.invoiceCode,
        invoiceTypeCode: invoiceData.invoiceTypeCode,
        invoiceKindCode: invoiceData.invoiceKindCode,
        invoiceStatusCode: invoiceData.invoiceStatusCode,
        isRedInvoice: invoiceData.isRedInvoice,
        sellerTaxNumber: invoiceData.sellerTaxNumber,
        sellerName: invoiceData.sellerName,
        buyerTaxNumber: invoiceData.buyerTaxNumber,
        buyerName: invoiceData.buyerName,
        invoiceDate: invoiceData.invoiceDate,
        totalAmount: invoiceData.totalAmount,
        taxAmount: invoiceData.taxAmount,
        totalTaxAmount: invoiceData.totalTaxAmount,
        invoiceSource: invoiceData.invoiceSource,
        issuer: invoiceData.issuer,
        taxBureauCode: invoiceData.taxBureauCode,
        taxBureauName: invoiceData.taxBureauName,
        organizationId: organizationId
      };
      
      if (existingInvoice) {
        // 更新现有发票
        await existingInvoice.update(invoicePayload);
        ctx.logger.info(`[IncomingInvoice] 更新发票: ${invoiceData.invoiceNumber}`);
        return existingInvoice;
      } else {
        // 创建新发票
        const newInvoice = await ctx.model.IncomingInvoiceModel.create(invoicePayload);
        ctx.logger.info(`[IncomingInvoice] 创建发票: ${invoiceData.invoiceNumber}`);
        return newInvoice;
      }
    } catch (error) {
      ctx.logger.error('[IncomingInvoice] 处理发票数据失败:', error);
      throw error;
    }
  }
  
  /**
   * 批量处理进项发票数据
   * @param {Array} invoiceList - 发票列表
   * @param {Number} organizationId - 组织ID
   */
  async batchProcessIncomingInvoices(invoiceList, organizationId) {
    const { ctx } = this;
    
    try {
      const results = {
        created: 0,
        updated: 0,
        failed: 0
      };
      
      for (const invoiceData of invoiceList) {
        try {
          const result = await this.createOrUpdateIncomingInvoice(invoiceData, organizationId);
          if (result.isNewRecord) {
            results.created++;
          } else {
            results.updated++;
          }
        } catch (error) {
          results.failed++;
          ctx.logger.error(`[IncomingInvoice] 处理发票失败: ${invoiceData.invoiceNumber}`, error);
        }
      }
      
      ctx.logger.info(`[IncomingInvoice] 批量处理完成 - 创建: ${results.created}, 更新: ${results.updated}, 失败: ${results.failed}`);
      return results;
    } catch (error) {
      ctx.logger.error('[IncomingInvoice] 批量处理发票失败:', error);
      throw error;
    }
  }
}

module.exports = IncomingInvoiceService;